package com.fr71.project.dm.listener;

import com.fr71.common.utils.spring.SpringUtils;
import com.fr71.project.dm.domain.PdOrder;
import com.fr71.project.dm.mapper.PdOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private PdOrderMapper orderMapper;

    public static final String KEY_ORDER_EXPIRATION = "order_exp_";

    private static final Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    private PdOrderMapper getOrderMapper() {
        if (orderMapper == null) {
            orderMapper = SpringUtils.getBean(PdOrderMapper.class);
        }
        return orderMapper;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        logger.debug("redis过期回调,{}", message);

        String expiredKey = new String(message.getBody(), StandardCharsets.UTF_8);

        if (expiredKey.startsWith(KEY_ORDER_EXPIRATION)) {
            //订单过期回掉
            String orderId = expiredKey.split(KEY_ORDER_EXPIRATION)[1];
            PdOrder order = getOrderMapper().selectPdOrderByOrderId(orderId);
            if (order != null) {
                if (order.getOrderStatus() == 0) {
                    order.setOrderStatus(2);
                    order.setRemark("订单超时未支付");
                    getOrderMapper().updatePdOrder(order);
                }
            }
        }
    }
}